package com.amkai.aes.webservice.binary.objecthandler.casehistory;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Query;

import com.amkai.aes.aescommon.service.binary.job.casehistory.PreferenceCardLoaderJob;
import com.amkai.aes.aescommon.service.binary.job.casehistory.PreferenceCardLoaderParams;
import com.amkai.aes.aescommon.service.binary.job.casehistory.PreferenceCardLoaderResult;
import com.amkai.aes.aescommon.service.binary.job.prefcards.PrefCardLazyResolver;
import com.amkai.aes.generatedbeans.preferencecard.PreferenceCard;
import com.amkai.aes.webservice.binary.JobObjectHandler;
import com.amkai.common.extensions.hibernate.config.SiteManager;
import com.amkai.common.extensions.hibernate.config.manager.SessionManager;

public class PreferenceCardLoaderHandler implements JobObjectHandler<PreferenceCardLoaderJob, PreferenceCardLoaderParams, PreferenceCardLoaderResult> {

	private static final Log logger = LogFactory.getLog(PreferenceCardLoaderHandler.class);

	private static String QUERY = "select prefCard from PreferenceCard prefCard where " + " prefCard.id in " + " ( select assoc.preferenceCard.id from AppointmentPreferenceCardAssociation assoc where assoc.abstractAppointment = :appointment ) ";

	@Override
	public PreferenceCardLoaderResult process(final PreferenceCardLoaderJob job, final PreferenceCardLoaderParams param) throws Exception {

		PreferenceCardLoaderResult result = new PreferenceCardLoaderResult();
		result.setPreferenceCards(new ArrayList<PreferenceCard>());
		result.getPreferenceCards().clear();
		SessionManager sm = null;
		List<PreferenceCard> resultList = null;
		try {
			sm = SiteManager.Start();
			sm.openSession();

			Query q = sm.execute(PreferenceCardLoaderHandler.QUERY).setParameter("appointment", param.getAbsApp());
			List<?> items = q.list();
			resultList = new ArrayList<PreferenceCard>();
			for (Object item : items) {
				PreferenceCard card = (PreferenceCard) item;
				PrefCardLazyResolver.resolve(card);

				resultList.add(card);
			}

			if (resultList != null) {
				result.getPreferenceCards().addAll(resultList);
			}

		} catch (Exception e) {
			PreferenceCardLoaderHandler.logger.error("PreferenceCardQueryHandler: ", e);
			e.printStackTrace();
			throw e;
		} finally {
			if (sm != null) {
				sm.closeSession();
			}
		}
		return result;

	}

}
